import base64
import hashlib
import hmac
import json
import time
import uuid

import requests


class SpeechRecognitionClient:
    def __init__(self, app_id, app_key, base_url="http://127.0.0.1:37090/open/asr/offline"):
        self.app_id = app_id
        self.app_key = app_key
        self.base_url = base_url

    def generate_signature(self, timestamp):
        """生成签名"""
        # 根据API要求构建签名字符串（这里需要根据实际API文档调整）
        sign_str = f"{self.app_id}{timestamp}"
        # 使用HMAC-SHA256生成签名
        signature = hmac.new(
            self.app_key.encode('utf-8'),
            sign_str.encode('utf-8'),
            hashlib.sha256
        ).hexdigest()
        return signature

    def encode_audio_file(self, audio_file_path):
        """将音频文件编码为Base64"""
        try:
            with open(audio_file_path, 'rb') as audio_file:
                audio_data = audio_file.read()
                base64_audio = base64.b64encode(audio_data).decode('utf-8')
            return base64_audio
        except Exception as e:
            print(f"音频文件编码失败: {e}")
            return None

    def recognize_speech(self, audio_file_path, fs=16000, audio_format="wav",
                         itn=False, speaker=False,combine_sentence=False,timestamp=False,
                         read_timeout=5000,hotword_id=None, enable_callback=0, callback_url=None):
        """
        语音识别请求

        参数:
        - audio_file_path: 音频文件路径
        - fs: 采样率 (8000 或 16000)
        - audio_format: 音频格式 (pcm, wav, ulaw, alaw)
        - itn: 是否进行数字转换
        - punc: 是否添加标点
        - speaker: 是否启用声纹识别
        - read_timeout: 读取超时时间(ms)
        - max_seconds: 最长识别时间(ms)
        - hotword_id: 热词ID
        - save: 是否保存识别记录
        """

        # 编码音频文件
        base64_audio = self.encode_audio_file(audio_file_path)
        if not base64_audio:
            return None

        # 生成时间戳和签名
        ts = str(int(time.time() * 1000))
        signature = self.generate_signature(ts)

        # 构建请求头
        headers = {
            'Content-Type': 'application/json',
            'Authorization': f'Access={self.app_id},Signature={signature}'
        }

        # 构建请求体
        payload = {
            'fs': fs,
            'format': audio_format,
            'itn': itn,
            'speaker': speaker,
            'combineSentence': combine_sentence,
            'timestamp':timestamp,
            'enableCallback': enable_callback,
            'callbackUrl': callback_url,
            'wav': base64_audio
        }

        # 添加可选参数
        if hotword_id is not None:
            payload['hotwordId'] = hotword_id

        try:
            # 发送POST请求
            response = requests.post(
                self.base_url,
                headers=headers,
                data=json.dumps(payload),
                timeout=(read_timeout / 1000 + 10)  # 设置请求超时
            )

            # 检查响应状态
            if response.status_code == 200:
                result = response.json()
                return result
            else:
                print(f"请求失败，状态码: {response.status_code}")
                print(f"响应内容: {response.text}")
                return None

        except requests.exceptions.RequestException as e:
            print(f"网络请求异常: {e}")
            return None
        except json.JSONDecodeError as e:
            print(f"JSON解析异常: {e}")
            return None


def main():
    # 配置参数 - 请替换为您的实际参数
    APP_ID = "13"
    APP_KEY = "your_app_key_here"
    AUDIO_FILE_PATH = "/Works/source/rmd-open-doc/python-demo/outputs/output_audio.wav"  # 替换为您的音频文件路径

    # 创建客户端实例
    client = SpeechRecognitionClient(APP_ID, APP_KEY)

    # 执行语音识别
    print("开始语音识别...")
    result = client.recognize_speech(
        audio_file_path=AUDIO_FILE_PATH,
        fs=16000,  # 采样率
        audio_format="pcm",  # 音频格式
        itn=True,  # 中文数字转阿拉伯数字
        speaker=False,  # 不启用声纹识别
        timestamp=True,  # 启用时间戳
        combine_sentence=True,  # 启用分句合并
        enable_callback=2,  # 回写方式
        callback_url=str(uuid.uuid4()),  # 唯一ID
    )

    # 处理结果
    print(result)


if __name__ == "__main__":
    main()